import datetime
import jwt
from django.conf.global_settings import SECRET_KEY

# SECRET_KEY

# 生成Token
def create_token():
    header = {
        "alg": "HS256",
        "typ": "JWT"
    }
    payload = {
      "user_id": "1",
      "user_name": "DPT",
      "exp": datetime.datetime.utcnow() + datetime.timedelta(minutes=1)
    }

    result = jwt.encode(headers=header, payload=payload, key=SECRET_KEY, algorithm='HS256')
    return result

# 验证Token
def get_payload(token):
    try :
        payload = jwt.decode(jwt=token, key=SECRET_KEY, algorithms=['HS256'])
        return payload
    except jwt.exceptions.ExpiredSignatureError:
        print('Token已经过期了')
    except jwt.exceptions.InvalidSignatureError:
        print('该Toke无效')
    except jwt.exceptions.DecodeError:
        print('Token验证失败了')

if __name__ == '__main__':
    # token = create_token()
    # print(token)
    token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoiMSIsInVzZXJfbmFtZSI6IkRQVCIsImV4cCI6MTcxMjIzNDUwMH0.zysfBy33YnVKsMpQDqWDn1nRL-GTCWJUPtsapntY0Ys'
    print(token)
    print(get_payload(token))